import { AntDesignTheme } from '@amcax/base';
import { ConfigProvider, Spin } from 'antd';
import { createRoot } from 'react-dom/client';
import styled from 'styled-components';

export const StyledLayout = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  z-index: 1000;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
`;
let count = 0;
let root = null;
let div = null;
let timer = null;
export default function showLoading() {
  if (count === 0) {
    const mountNode = document.getElementById('app-nextshape_root');
    div = document.createElement('div');
    div.className = 'loading';
    mountNode.appendChild(div);
    root = createRoot(div);

    root.render(
      // 因为这个是直接添加到body，所以需要使用ConfigProvider，保持样式统一
      <ConfigProvider theme={AntDesignTheme}>
        <StyledLayout>
          <Spin tip='Loading...'>
            <div className='content' />
          </Spin>
        </StyledLayout>
      </ConfigProvider>,
    );
    createTimer();
  }
  count++;
  return hide;
}

const hide = () => {
  count--;
  if (count > 0) {
    createTimer();
  } else {
    destroy();
  }
};
// 超时时间5分钟
const timeout = 1000 * 60 * 5;
const createTimer = () => {
  timer && clearTimeout(timer);
  timer = setTimeout(() => {
    destroy();
  }, timeout);
};

const destroy = () => {
  root?.unmount();
  div?.parentNode?.removeChild(div);
  timer && clearTimeout(timer);
  timer = null;
  root = null;
  div = null;
  count = 0;
};
